package cn.com.cpic.insurance.rulecheck.core.element;

import javax.el.ELException;

import org.apache.el.parser.ELParser;
import org.apache.el.parser.Node;

import cn.com.cpic.insurance.rulecheck.core.Context;
import cn.com.cpic.insurance.rulecheck.core.exception.BomNotFoundException;
import cn.com.cpic.insurance.rulecheck.core.exception.OperateException;

/**
 * 
 * 
 * @author 代波
 * @since 2011-8-20
 */
public final class BOMParameterElement extends ParameterElement {
	private static final long serialVersionUID = 5106825865461581938L;

	private final Node node;

	public BOMParameterElement(String parameterToken) {
		super(parameterToken);
		this.node = ELParser.parse(parameterToken);
	}

	public final Comparable<?> operate(Context context) throws OperateException {
		Object result;
		try {
			result = node.getValue(context.getEvaluationContext());
		} catch (ELException e) {
			throw new IllegalArgumentException("无法解析bom参数！parameterToken=" + getParameterToken(), e);
		}
		if (result == null) {
			throw new BomNotFoundException(getParameterToken());
		} else {
			if (Long.class.isInstance(result)) {
				return new Long((Long) result);
			} else if (Integer.class.isInstance(result)) {
				return new Long((Integer) result);
			} else if (Double.class.isInstance(result)) {
				return new Double((Double) result);
			} else if (Boolean.class.isInstance(result)) {
				return new Boolean((Boolean) result);
			} else if (String.class.isInstance(result)) {
				return new String((String) result);
			} else {
				throw new IllegalArgumentException("未知的值类型！parameterToken=" + getParameterToken() + ", type="
						+ result.getClass());
			}
		}
	}
}
